package org.yyf.resource.demo.socket;

import java.io.IOException;
import java.net.Socket;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * MML socket 客户端
 * @author YYF
 *
 */

@Service
public class SocketClient {
	
	private final static Logger log = LoggerFactory.getLogger(SocketClient.class) ;
	
	private final static String QUERY_C280_USER = "QUERY C280 USER:LOGINNAME={0}@jtkd";
	
	private final static String QUERY_C280_USERSESS = "QUERY C280 USERSESS:DOMAIN=jtkd,USERNAME={0},SERVICEFLAG=AAA";
	
	private final static String ATTR_REGEX = "ATTR=([\\s\\S])*?,";
	
	private final static String RESULT_REGEX = "RESULT=\"([\\s\\S])*?\"";
	
	/**
	 * socket 查询用户信息命令
	 * @param loginName 登录名
	 */
	public String userMmlRequest(String loginName,String ip,int port) {
		String userMml = MessageFormat.format(QUERY_C280_USER, loginName);
		
		//服务端返回的结果数据
		String data = socketRequest(userMml,ip,port);
		
		String lastUseEndTime = "";
		
		if(StringUtils.isNotBlank(data)) {
			log.info(data);
			
			String attr = getStrWithRegex(data,ATTR_REGEX);
			String result = getStrWithRegex(data,RESULT_REGEX);
			int index = 0;
			
			if(StringUtils.isNotBlank(attr)) {
				String[] a = attr.split("&");
				for(int i =0 ;i<a.length;i++) {
					if(a[i].equals("LASTUSEENDTIME")) {
						index = i;
					}
				}
			}
			
			if(StringUtils.isNotBlank(result)) {
				String[] r = result.split("\\|");
				lastUseEndTime= r[index];
			}
		}
		
		
		return lastUseEndTime;
	}
	
	/**
	 * socket 查询用户会话信息命令
	 * @param loginName	登录名
	 * @param ip		socket地址
	 * @param port		socket端口
	 * @return
	 */
	public String userSessMmlRequest(String loginName,String ip,int port) {
		String userSessMml = MessageFormat.format(QUERY_C280_USERSESS, loginName);
		//服务端返回的结果数据
		String data = socketRequest(userSessMml,ip,port);
		//SERSTARTTIME
		String  serStartTime ="";
		
		if(StringUtils.isNotBlank(data)) {
			log.info(data);
			
			String attr = getStrWithRegex(data,ATTR_REGEX);
			String result = getStrWithRegex(data,RESULT_REGEX);
			int index = 0;
			
			if(StringUtils.isNotBlank(attr)) {
				String[] a = attr.split("&");
				for(int i =0 ;i<a.length;i++) {
					if(a[i].equals("SERSTARTTIME")) {
						index = i;
					}
				}
			}
			
			if(StringUtils.isNotBlank(result)) {
				String[] r = result.split("\\|");
				serStartTime= r[index];
			}
		}
		
		return serStartTime;
	}
	
	
	private static String socketRequest(String message,String ip,int port) {
		String result = "";
		Socket socket = null;
		try {
			
			// 与服务端建立连接
			socket = new Socket(ip, port);
			// 建立连接后获得输出流
			socket.getOutputStream().write(message.getBytes("UTF-8"));
			// 通过shutdownOutput高速服务器已经发送完数据，后续只能接受数据
			socket.shutdownOutput();
			
			byte[] bytes = new byte[1024];
			int len;
			StringBuffer str = new StringBuffer();
			while ((len = socket.getInputStream().read(bytes)) != -1) {
				str.append(new String(bytes, 0, len, "UTF-8"));
			}
			
			result = str.toString();
			
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}finally {
			if(socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					log.error(e.getMessage(),e);
				}
			}
		}
		
		return result;
	}
	
	/**
	 * 返回str中匹配 正则表达式 的第一个匹配值
	 * @param str
	 * @param regex
	 * @return
	 */
	private static String getStrWithRegex(String str,String regex) {
		
		str = str.replaceAll("\\s", "");
		
		Pattern pattern=Pattern.compile(regex); 
		
		Matcher matcher=pattern.matcher(str); 
		
		while(matcher.find()) {
			str = matcher.group();
		}
		
		return str;
	}

	
	/**
	 * 测试运行
	 * @param args
	 * @throws Exception
	 */
	public static void main(String args[]) throws Exception {
		
		String  result = "QUERY C280 USER: RETN=0, DESC=\"查询用户成功。\", TOTAL=1, FINISHED=1, START=0, ROWNUM=1, ATTR=LOGINNAME & ACCOUNTNUMBER & USERID & USERNAME & IDNUMBER & CONTACTMAN & PAYMODE & COMPANY & USERADDRESS & BANK & BANKACCOUNT & PHONE & PAYPHONE & ACCOUNTTYPE & ACCESSRIGHT & ZIPCODE & MOBILE & EMAIL & BP & DESCRIPTION & SERVICELEVEL & MAXUSERNUMBER & IPADDRESS & IPMASK & STATUS & TEMPLATEID & TEMPLATENAME & IPPOOLID & IPPOOLT........ & NASIDENTIFY & NASPORTID & VLANID & LASTUSEBEGINTIME & LASTUSEENDTIME & IWLANAUTHENABLED & IMSI & MSISDN & AREANAME & ACCESSPOLICYNAME & AUTHTYPE & FRAINTERFACEID & FRAIPV6PREFIX & DELIPV6PRE & FRAIPV6ADDR & IPADDRESSSTR & IPMASKSTR & CVLANID & QUANTITYVOLUM & STOPREASON, RESULT=\"lcl@-1|20140219011800000005|20140219011800000005||||1||||||||||||||2|1|-1|-1|1|-1||-1|||0||-1|-1|200000|-1||20140219155126||1|0|20140219155126|20380101000000|0|lcl|0||0|||00000000000000|||0||-1|0|1|0||||-1|||0|||||1|||||255.255.255.255|255.255.255.255|||0|\",;";
		
		result = result.replaceAll("\\s", "");
//		result = result.replaceAll("\\n", "");
		
		String attr = getStrWithRegex(result,"ATTR=([\\s\\S])*?,");
		System.out.println(attr);
		
		String RESULT="18307218756@jtkd|18307218756@jtkd||5170948328|5170948328||1|||||5170948328||1|3||5170948328|null|||1|1|-1|-1|1|71|100M-NEW01|-1|||1|11432-trunk1/1/4:2056.269210.94.40.49/0/0/18/0/3/00000000434D4443B2AF1173GP^B|-1|-1|200000|-1||20190201092253|20370101000000|1|0|999999999||0||0||0|20190201180959||00000000000000|0||11|0|1|9|223.75.75.15|HBXYA-MC-CMNET-BAS15-GC-ME60-|trunk1/1/4:2056.269210.94.40.49/0/0/18/0/3/00000000434D4443B2AF1173GP^B|-1||20190823110943|0|******||||1|||||0|0|255.255.255.255|255.255.255.255|-1|0|0|";
		String[] r=RESULT.split("\\|");
		System.out.println(r.length);
		
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
		LocalDateTime startTime = LocalDateTime.parse("20190825000000",formatter);
		System.out.println(startTime);
		
	}
}
